package com.nickstumpos.android.GmailWidgetPlus.Configure.OptionsList.options;

import java.util.ArrayList;
import java.util.List;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.nickstumpos.android.GmailWidgetPlus.Configure.OptionsList.OptionsList;
import com.nickstumpos.android.GmailWidgetPlus.Constants.GMWP_Constants;
import com.nickstumpos.android.GmailWidgetPlus.gmailProvider.GmailProvider;
import com.nickstumpos.android.GmailWidgetPlus.labels.LabelBlackListManager;
import com.nickstumpos.android.GmailWidgetPlus.labels.SystemLabels;

public class LabelsOptionList extends OptionsList {

	private List<String>	labelNames;

	public LabelsOptionList(final Context context,
			final int widgetId,
			final String title) {

		super(context, widgetId, title);
	}

	@Override
	protected void initializeArrayAdaptor() {

		this.setAa(new ArrayAdapter<String>(this.getContext(),
				android.R.layout.simple_list_item_multiple_choice));
	}

	@Override
	protected void save() {

		for (int i = 0; i < this.getAa().getCount(); i++) {
			if (this.getCheckedItemPositions().get(i + 1)) {
				LabelBlackListManager.blacklist(this.labelNames.get(i),
						this.getWidgetId());
			}
		}
		LabelBlackListManager.commitBlacklist(this.getContext(),
				this.getWidgetId());
	}

	@Override
	protected void setupDialog() {

		final List<Integer> positionsChecked = new ArrayList<Integer>();
		int index = 1;
		String name = this.getPrefs()
				.getString(GMWP_Constants.PREF_ACCOUNT_REF + this.getWidgetId(),
						null);
		if (name == null) {
			final Account[] accounts = AccountManager.get(this.getContext())
					.getAccountsByType(GMWP_Constants.GOOGLE_ACCOUNT_TYPE);
			if ((accounts != null) && (accounts[0] != null)) {
				name = accounts[0].name;
			}
		}
		if (name != null) {
			this.labelNames = new GmailProvider(this.getContext(),
					name,
					false,
					null).getLabelsNames();
			for (final String s : this.labelNames) {
				SystemLabels sl = null;
				if (s.startsWith(GMWP_Constants.SYSTEM_LABEL_PREFIX)) {
					sl = SystemLabels.systemLabelByCode(s);
					if (sl != null) {
						this.getAa().add(sl.getName());
					}
				} else {
					this.getAa().add(s);
				}
				if (LabelBlackListManager.isBlacklisted(s, this.getWidgetId())) {
					positionsChecked.add(index);
				}
				index++;
			}
			this.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			for (final Integer pos : positionsChecked) {
				this.setItemChecked(pos, true);
			}
		}
	}
}
